﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformEntity;
using Webdiyer.WebControls.Mvc;
using System.IO;
using System.Text;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformWeb.Controllers.RealTime;

namespace MinistryStandardPlatformWeb.Controllers
{
    [IsLogin]
    public class VehicleController : Controller
    {
        //
        // GET: /Vehicle/
        private MSPDataContext context = new MSPDataContext();

        [MenuAuthorized("12")]
        public ActionResult Index()
        {
            var rights = from r in context.RightsDetails
                         where r.UserId == CommonFunctions.GetLoginUser().UserId &&
                         //r.HasRight == true &&
                         r.NodeTYPE == false
                         select r;
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                string id = HttpUtility.UrlDecode(Request.QueryString["id"]);
                rights = from r in rights
                         where r.ParentNodeId == id
                         select r;
            }

            var vehicles = from r in rights
                           from v in context.InfoVehicle
                           where v.Vehiclenum == r.NodeId
                           orderby v.Finsertdate descending
                           select v;

            Session["vehiclelist"] = vehicles.ToList();
            var vlist = vehicles.ToPagedList(1, CommonDictionary.PageSize);
            foreach(InfoVehicle v in vlist)
            {
                string name1,name2;
                CommonDictionary.GpsTypeDic.TryGetValue(v.GPSType.ToString(),out name1);
                v.GPSTypeName = name1;
                CommonDictionary.GpsVersionDic.TryGetValue(v.GPSType.ToString()+v.GPSVersion.ToString(), out name2);
                v.GPSVersionName = name2;
            }

            //if (Request.IsAjaxRequest())
            //    return PartialView("_Index", vlist);
            return PartialView(vlist);
        }

        [MenuAuthorized("124")]
        public ActionResult Data(string condition, string unitId, string searchAll, int pageIndex = 1)
        {
            var rights = from r in context.RightsDetails
                         where r.UserId == CommonFunctions.GetLoginUser().UserId &&
                         //r.HasRight == true &&
                         r.NodeTYPE == false
                         select r;
            if (!string.IsNullOrEmpty(unitId) && searchAll != "on")
            {
                rights = from r in rights
                         where r.ParentNodeId == unitId
                         select r;

            }

            if (!string.IsNullOrEmpty(unitId) && searchAll == "on")
            {
                List<string> ids = CommonFunctions.GetAllChildrenUnits(unitId, CommonFunctions.GetLoginUser().UserId);
                ids.Add(unitId);
                rights = from r in rights
                         where ids.Contains(r.ParentNodeId)
                         select r;

            }

            var vehicles = from r in rights
                           from v in context.InfoVehicle
                           where v.Vehiclenum == r.NodeId
                           orderby v.ParentUnitId, v.Finsertdate descending
                           select v;

            if (!string.IsNullOrEmpty(condition))
            {
                vehicles = from v in vehicles
                           where v.VehicleId.Contains(condition) ||
                           v.FInnerId.Contains(condition) ||
                           v.SIM.Contains(condition)
                           orderby v.ParentUnitId, v.Finsertdate descending
                           select v;
            }
            Session["vehiclelist"] = vehicles.ToList();
            var vlist = vehicles.ToPagedList(pageIndex, CommonDictionary.PageSize);
            foreach (InfoVehicle v in vlist)
            {
                string name1, name2;
                CommonDictionary.GpsTypeDic.TryGetValue(v.GPSType.ToString(), out name1);
                v.GPSTypeName = name1;
                CommonDictionary.GpsVersionDic.TryGetValue(v.GPSType.ToString() + v.GPSVersion.ToString(), out name2);
                v.GPSVersionName = name2;
            }
            return PartialView(vlist);
        }

        [MenuAuthorized("121")]
        public ActionResult Create()
        {
            string unitId = HttpUtility.UrlDecode(Request.QueryString["unitId"]);
            string unitName = HttpUtility.UrlDecode(Request.QueryString["unitName"]);

            //车辆类型
            ViewBag.VehicleType =
                context.Dictionary_Detail.Where(d => d.TypeID == "zd001").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicName,
                }).ToList();

            //终端类型(默认选中部标协议）
            ViewBag.GpsType =
                context.Dictionary_Detail.Where(d => d.TypeID == "gpstype").OrderBy(d=>d.DicValue).AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicValue,
                    Selected = d.DicID == "bbxy"
                }).ToList();

            //终端版本号
            ViewBag.GpsVersion =
                context.Dictionary_Detail.Where(d => d.TypeID == "gpsversion" && d.Memo == "2").OrderBy(d => d.DicValue).AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicValue,
                    Selected = d.DicID == "bzbb"
                }).ToList();

            //行驶记录仪版本号
            ViewBag.TerminalVersion =
                context.Dictionary_Detail.Where(d => d.TypeID == "terminalversion").OrderByDescending(d=>d.DicID).AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicValue,
                    Selected = d.DicID == "xsjly2012"
                }).ToList();

            //车辆品牌
            ViewBag.VehicleBrand =
                context.Dictionary_Detail.Where(d => d.TypeID == "zd003").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicName,
                    Selected=false
                }).ToList();

            //车辆颜色
            ViewBag.VehicleColor =
                context.Dictionary_Detail.Where(d => d.TypeID == "zd006").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicName,
                    Selected = false
                }).ToList();

            //安装人员
            ViewBag.InstallStaffId =
                context.InfoStaff.Where(s => s.StaffType == "installstaff").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.StaffName,
                    Value = d.StaffId,
                    Selected = false
                }).ToList();

            return View(new InfoVehicle()
            {
                InstallUnitId = unitId,
                ParentUnitId = unitId,
                InfoUnit = new InfoUnit() { UNITID = unitId, UNITNAME = unitName },
                InfoUnit1 = new InfoUnit() { UNITID = unitId, UNITNAME = unitName }
            });
        }

        public ActionResult PickParentUnit()
        {
            var units = context.RightsDetails.Where(u => u.UserId == CommonFunctions.GetLoginUser().UserId && u.NodeTYPE == true).Select(u => new { NodeId = u.NodeId, ParentNodeId = u.ParentNodeId, NodeName = u.NodeName });
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var unit in units)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = unit.NodeId;
                node.pId = unit.ParentNodeId;
                node.name = unit.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                if (unit.ParentNodeId == null)
                {
                    node.open = true;
                }
                else
                {
                    node.open = false;
                }
                nodes.Add(node);
            }
            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        public ActionResult PickInstallUnit()
        {
            var units = context.RightsDetails.Where(u => u.UserId == CommonFunctions.GetLoginUser().UserId && u.NodeTYPE == true).Select(u => u);
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var unit in units)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = unit.NodeId;
                node.pId = unit.ParentNodeId;
                node.name = unit.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                if (unit.ParentNodeId == null)
                {
                    node.open = true;
                }
                else
                {
                    node.open = false;
                }
                nodes.Add(node);
            }
            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        [HttpPost]
        [MenuAuthorized("121")]
        public ActionResult Create(FormCollection form)
        {
            InfoVehicle vehicle = new InfoVehicle();
            try
            {
                if (context.InfoVehicle.Any(v => v.VehicleId == form["VehicleId"]))
                {
                    ViewBag.Message = "添加失败,已经存在车牌号为" + form["VehicleId"] + "的车辆";
                    //车辆类型
                    ViewBag.VehicleType =
                        context.Dictionary_Detail.Where(d => d.TypeID == "zd001").AsEnumerable()
                        .Select(d => new SelectListItem
                        {
                            Text = d.DicName,
                            Value = d.DicName,
                        }).ToList();

                    //终端类型(默认选中部标协议）
                    ViewBag.GpsType =
                        context.Dictionary_Detail.Where(d => d.TypeID == "gpstype").OrderBy(d => d.DicValue).AsEnumerable()
                        .Select(d => new SelectListItem
                        {
                            Text = d.DicName,
                            Value = d.DicValue,
                            Selected = d.DicID == "bbxy"
                        }).ToList();

                    //终端版本号
                    ViewBag.GpsVersion =
                        context.Dictionary_Detail.Where(d => d.TypeID == "gpsversion" && d.Memo == "bbxy").OrderBy(d => d.DicValue).AsEnumerable()
                        .Select(d => new SelectListItem
                        {
                            Text = d.DicName,
                            Value = d.DicValue,
                            Selected = d.DicID == "bzbb"
                        }).ToList();

                    //行驶记录仪版本号
                    ViewBag.TerminalVersion =
                        context.Dictionary_Detail.Where(d => d.TypeID == "terminalversion").OrderByDescending(d => d.DicID).AsEnumerable()
                        .Select(d => new SelectListItem
                        {
                            Text = d.DicName,
                            Value = d.DicValue,
                            Selected = d.DicID == "xsjly2012"
                        }).ToList();

                    //车辆品牌
                    ViewBag.VehicleBrand =
                        context.Dictionary_Detail.Where(d => d.TypeID == "zd003").AsEnumerable()
                        .Select(d => new SelectListItem
                        {
                            Text = d.DicName,
                            Value = d.DicName,
                            Selected = false
                        }).ToList();

                    //车辆颜色
                    ViewBag.VehicleColor =
                        context.Dictionary_Detail.Where(d => d.TypeID == "zd006").AsEnumerable()
                        .Select(d => new SelectListItem
                        {
                            Text = d.DicName,
                            Value = d.DicName,
                            Selected = false
                        }).ToList();

                    //安装人员
                    ViewBag.InstallStaffId =
                        context.InfoStaff.Where(s => s.StaffType == "installstaff").AsEnumerable()
                        .Select(d => new SelectListItem
                        {
                            Text = d.StaffName,
                            Value = d.StaffId,
                            Selected = false
                        }).ToList();
                }
                else
                {
                    UpdateModel(vehicle, form.ToValueProvider());
                    vehicle.Vehiclenum = "VEHI" + CommonFunctions.GetDateTimeStrAnd4BitsRandom();
                    vehicle.Finsertdate = DateTime.Now;
                    vehicle.VehicleState = 0;

                    //sim卡号前面要补一位0
                    if (vehicle.SIM.Length == 11)
                    {
                        vehicle.SIM = "0" + vehicle.SIM;
                    }
                    this.context.InfoVehicle.InsertOnSubmit(vehicle);

                    //添加后要将本车辆的权限授予自己
                    //RightsDetails right = new RightsDetails();
                    //right.UserId = CommonFunctions.GetLoginUser().UserId;
                    //right.NodeId = vehicle.Vehiclenum;
                    //right.NodeName = vehicle.VehicleId + "," + vehicle.FInnerId;
                    //right.ParentNodeId = vehicle.ParentUnitId;
                    //right.NodeTYPE = false;
                    //right.HasRight = true;
                    //context.RightsDetails.InsertOnSubmit(right);
                    
                    /*将车辆权限授予有该单位权限的所有用户*/
                    List<RightsDetails> hasUnitRightList = this.context.RightsDetails.Where(t => t.NodeId == vehicle.ParentUnitId && t.HasRight == true).ToList();
                    foreach (RightsDetails rd in hasUnitRightList)
                    {
                        RightsDetails right = new RightsDetails();
                        right.NodeId = vehicle.Vehiclenum;
                        right.NodeName = vehicle.VehicleId + "," + vehicle.FInnerId;
                        right.ParentNodeId = vehicle.ParentUnitId;
                        right.NodeTYPE = false;
                        right.HasRight = true;
                        right.UserId = rd.UserId;
                        right.InsertUserID = CommonFunctions.GetLoginUser().UserId;
                        this.context.RightsDetails.InsertOnSubmit(right);
                    }
                    this.context.SubmitChanges();
                    ViewBag.Message = "添加成功";

                    List<SelectListItem> items = new List<SelectListItem>();
                    items.Add(new SelectListItem());

                    //车辆类型
                    ViewBag.VehicleType = new SelectList(items);

                    //终端类型(默认选中部标协议）
                    ViewBag.GpsType = new SelectList(items);

                    //终端版本号
                    ViewBag.GpsVersion = new SelectList(items);

                    //行驶记录仪版本号
                    ViewBag.TerminalVersion = new SelectList(items);

                    //车辆品牌
                    ViewBag.VehicleBrand = new SelectList(items);

                    //车辆颜色
                    ViewBag.VehicleColor = new SelectList(items);

                    //安装人员
                    ViewBag.InstallStaffId = new SelectList(items);

                    //通知业务中心终端类型的改变
                    try
                    {
                        updateGpsType(vehicle);
                    }
                    catch
                    {
                        //车辆类型
                        ViewBag.VehicleType =
                            context.Dictionary_Detail.Where(d => d.TypeID == "zd001").AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicName,
                            }).ToList();

                        //终端类型(默认选中部标协议）
                        ViewBag.GpsType =
                            context.Dictionary_Detail.Where(d => d.TypeID == "gpstype").OrderBy(d => d.DicValue).AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicValue,
                                Selected = d.DicID == "bbxy"
                            }).ToList();

                        //终端版本号
                        ViewBag.GpsVersion =
                            context.Dictionary_Detail.Where(d => d.TypeID == "gpsversion" && d.Memo == "bbxy").OrderBy(d => d.DicValue).AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicValue,
                                Selected = d.DicID == "bzbb"
                            }).ToList();

                        //行驶记录仪版本号
                        ViewBag.TerminalVersion =
                            context.Dictionary_Detail.Where(d => d.TypeID == "terminalversion").OrderByDescending(d => d.DicID).AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicValue,
                                Selected = d.DicID == "xsjly2012"
                            }).ToList();

                        //车辆品牌
                        ViewBag.VehicleBrand =
                            context.Dictionary_Detail.Where(d => d.TypeID == "zd003").AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicName,
                                Selected = false
                            }).ToList();

                        //车辆颜色
                        ViewBag.VehicleColor =
                            context.Dictionary_Detail.Where(d => d.TypeID == "zd006").AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicName,
                                Selected = false
                            }).ToList();

                        //安装人员
                        ViewBag.InstallStaffId =
                            context.InfoStaff.Where(s => s.StaffType == "installstaff").AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.StaffName,
                                Value = d.StaffId,
                                Selected = false
                            }).ToList();

                        ViewBag.Message = "添加成功，发业务中心消息失败";
                    }

                }
            }
            catch (System.Exception ex)
            {
                ViewBag.Message = "添加失败," + ex.Message;
                //车辆类型
                ViewBag.VehicleType =
                    context.Dictionary_Detail.Where(d => d.TypeID == "zd001").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicName,
                    }).ToList();

                //终端类型(默认选中部标协议）
                ViewBag.GpsType =
                    context.Dictionary_Detail.Where(d => d.TypeID == "gpstype").OrderBy(d=>d.DicValue).AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicValue,
                        Selected = d.DicID == "bbxy"
                    }).ToList();

                //终端版本号
                ViewBag.GpsVersion =
                    context.Dictionary_Detail.Where(d => d.TypeID == "gpsversion" && d.Memo == "bbxy").OrderBy(d => d.DicValue).AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicValue,
                        Selected = d.DicID == "bzbb"
                    }).ToList();

                //行驶记录仪版本号
                ViewBag.TerminalVersion =
                    context.Dictionary_Detail.Where(d => d.TypeID == "terminalversion").OrderByDescending(d => d.DicID).AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicValue,
                        Selected = d.DicID == "xsjly2012"
                    }).ToList();

                //车辆品牌
                ViewBag.VehicleBrand =
                    context.Dictionary_Detail.Where(d => d.TypeID == "zd003").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicName,
                        Selected = false
                    }).ToList();

                //车辆颜色
                ViewBag.VehicleColor =
                    context.Dictionary_Detail.Where(d => d.TypeID == "zd006").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicName,
                        Selected = false
                    }).ToList();

                //安装人员
                ViewBag.InstallStaffId =
                    context.InfoStaff.Where(s => s.StaffType == "installstaff").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.StaffName,
                        Value = d.StaffId,
                        Selected = false
                    }).ToList();
            }

            return View(vehicle);

        }

        [MenuAuthorized("122")]
        public ActionResult Delete(string parameters)
        {
            var vehicle = context.InfoVehicle.SingleOrDefault(v => v.Vehiclenum == parameters);
            //对应的权限表中的数据通过数据库触发器来删除
            try
            {
                context.InfoVehicle.DeleteOnSubmit(vehicle);
                context.SubmitChanges();
                return Json(new { success = "true", message = "" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = "false", message = ex.Message });
            }
        }

        [MenuAuthorized("123;125")]
        public ActionResult Edit(string id)
        {
            var vehicle = context.InfoVehicle.SingleOrDefault(v => v.Vehiclenum == id);

            //车辆类型
            ViewBag.VehicleType =
                context.Dictionary_Detail.Where(d => d.TypeID == "zd001").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicName,
                    Selected = d.DicName == vehicle.VehicleType
                }).ToList();

            ViewBag.GpsType =
                context.Dictionary_Detail.Where(d => d.TypeID == "gpstype").OrderBy(d => d.DicValue).AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicValue,
                    Selected = d.DicValue==vehicle.GPSType.ToString()
                }).ToList();

            //终端版本号
            ViewBag.GpsVersion =
                context.Dictionary_Detail.Where(d => d.TypeID == "gpsversion" && d.Memo==vehicle.GPSType.ToString()).OrderBy(d => d.DicValue).AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicValue,
                    Selected = d.DicValue==vehicle.GPSVersion.ToString()
                }).ToList();

            //行驶记录仪版本号
            ViewBag.TerminalVersion =
                context.Dictionary_Detail.Where(d => d.TypeID == "terminalversion" && d.Memo == vehicle.GPSType.ToString()).OrderByDescending(d => d.DicID).AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicValue,
                    Selected = d.DicID == vehicle.TerminalVersion.ToString()
                }).ToList();

            //车辆品牌
            ViewBag.VehicleBrand =
                context.Dictionary_Detail.Where(d => d.TypeID == "zd003").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicName,
                    Selected = d.DicName==vehicle.VehicleBrand
                }).ToList();

            //车辆颜色
            ViewBag.VehicleColor =
                context.Dictionary_Detail.Where(d => d.TypeID == "zd006").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.DicName,
                    Value = d.DicName,
                    Selected = d.DicName==vehicle.VehicleColor
                }).ToList();

            //安装人员
            ViewBag.InstallStaffId =
                context.InfoStaff.Where(s => s.StaffType == "installstaff").AsEnumerable()
                .Select(d => new SelectListItem
                {
                    Text = d.StaffName,
                    Value = d.StaffId,
                    Selected = d.StaffId==vehicle.InstallStaffId
                }).ToList();

            //显示时要去掉sim卡号前面的0
            if (vehicle.SIM.Length == 12 && vehicle.SIM.StartsWith("0"))
            {
                vehicle.SIM = vehicle.SIM.Substring(1);
            }

            return View(vehicle);
        }

        [HttpPost]
        [MenuAuthorized("123;125")]
        public ActionResult Edit(FormCollection form)
        {
            try
            {
                var vehicleToUpdate = context.InfoVehicle.SingleOrDefault(v => v.Vehiclenum == form["Vehiclenum"]);
                string oldUnitId = vehicleToUpdate.ParentUnitId;
                string newUnitId = form["ParentUnitId"];

                bool gpsUpdated=false;
                if(vehicleToUpdate.GPSType.ToString()!=form["GPSType"] ||
                    vehicleToUpdate.GPSVersion.ToString()!=form["GPSVersion"] ||
                    vehicleToUpdate.IsOffBump.ToString()!=form["IsOffBump"] ||
                    vehicleToUpdate.TerminalVersion.ToString()!=form["TerminalVersion"])
                {
                    gpsUpdated=true;
                }
                UpdateModel(vehicleToUpdate, form.ToValueProvider());
                //sim卡号前面要补一位0
                if (vehicleToUpdate.SIM.Length == 11)
                {
                    vehicleToUpdate.SIM = "0" + vehicleToUpdate.SIM;
                }
                //最近更新时间
                vehicleToUpdate.Finsertdate = DateTime.Now;

                //if (!oldUnitId.Equals(newUnitId))
                //{
                //    //该车辆的所有用户权限
                //    List<RightsDetails> hasVehcleRight = this.context.RightsDetails.Where(t => t.NodeId == form["Vehiclenum"]).ToList();
                //    //新单位的所有用户权限
                //    List<RightsDetails> hasNewUnitRight = this.context.RightsDetails.Where(t => t.NodeId == form["ParentUnitId"]).ToList();
                //    foreach (RightsDetails vrd in hasVehcleRight)
                //    {
                //        bool hasFind = false;
                //        foreach (RightsDetails urd in hasNewUnitRight)
                //        {
                //            if (vrd.UserId.Equals(urd.UserId))
                //            {//拥有该车辆权限的用户又拥有该新单位权限
                //                vrd.ParentNodeId = urd.NodeId;//修改父节点id
                //                hasFind = true;
                //            }
                //        }
                //        if (!hasFind)
                //        {//用户改车辆权限的用户没有该新单位的权限
                //            vrd.ParentNodeId = null;//修改父节点为根节点
                //        }
                //        vrd.InsertUserID = CommonFunctions.GetLoginUser().UserId;
                //    }
                //    //如果拥有新单位权限的用户没有该车辆的权限，添加车辆权限
                //    foreach (RightsDetails urd in hasNewUnitRight)
                //    {
                //        bool hasFind = false;
                //        foreach (RightsDetails vrd in hasVehcleRight)
                //        {
                //            if (urd.UserId.Equals(vrd.UserId))
                //            {
                //                hasFind = true;
                //                break;
                //            }
                //        }
                //        if (!hasFind)
                //        {
                //            RightsDetails right = new RightsDetails();
                //            right.NodeId = vehicleToUpdate.Vehiclenum;
                //            right.NodeName = vehicleToUpdate.VehicleId + "," + vehicleToUpdate.FInnerId;
                //            right.ParentNodeId = newUnitId;
                //            right.NodeTYPE = false;
                //            right.HasRight = true;
                //            right.UserId = urd.UserId;
                //            right.InsertUserID = CommonFunctions.GetLoginUser().UserId;
                //            this.context.RightsDetails.InsertOnSubmit(right);
                //        }
                //    }
                //}
                context.SubmitChanges();
                ViewBag.Message = "修改成功";

                //通知业务中心终端类型的改变
                if (gpsUpdated)
                {
                    try
                    {
                        updateGpsType(vehicleToUpdate);
                        List<SelectListItem> items = new List<SelectListItem>();
                        items.Add(new SelectListItem());

                        //车辆类型
                        ViewBag.VehicleType = new SelectList(items);

                        //终端类型(默认选中部标协议）
                        ViewBag.GpsType = new SelectList(items);

                        //终端版本号
                        ViewBag.GpsVersion = new SelectList(items);

                        //行驶记录仪版本号
                        ViewBag.TerminalVersion = new SelectList(items);

                        //车辆品牌
                        ViewBag.VehicleBrand = new SelectList(items);

                        //车辆颜色
                        ViewBag.VehicleColor = new SelectList(items);

                        //安装人员
                        ViewBag.InstallStaffId = new SelectList(items);
                    }
                    catch
                    {
                        ViewBag.Message = "更改成功，发业务中心消息失败";
                        //车辆类型
                        ViewBag.VehicleType =
                            context.Dictionary_Detail.Where(d => d.TypeID == "zd001").AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicName,
                            }).ToList();

                        //终端类型(默认选中部标协议）
                        ViewBag.GpsType =
                            context.Dictionary_Detail.Where(d => d.TypeID == "gpstype").OrderBy(d => d.DicValue).AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicValue,
                                Selected = d.DicID == "bbxy"
                            }).ToList();

                        //终端版本号
                        ViewBag.GpsVersion =
                            context.Dictionary_Detail.Where(d => d.TypeID == "gpsversion" && d.Memo == "bbxy").OrderBy(d => d.DicValue).AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicValue,
                                Selected = d.DicID == "bzbb"
                            }).ToList();

                        //行驶记录仪版本号
                        ViewBag.TerminalVersion =
                            context.Dictionary_Detail.Where(d => d.TypeID == "terminalversion").OrderByDescending(d => d.DicID).AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicValue,
                                Selected = d.DicID == "xsjly2012"
                            }).ToList();

                        //车辆品牌
                        ViewBag.VehicleBrand =
                            context.Dictionary_Detail.Where(d => d.TypeID == "zd003").AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicName,
                                Selected = false
                            }).ToList();

                        //车辆颜色
                        ViewBag.VehicleColor =
                            context.Dictionary_Detail.Where(d => d.TypeID == "zd006").AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.DicName,
                                Value = d.DicName,
                                Selected = false
                            }).ToList();

                        //安装人员
                        ViewBag.InstallStaffId =
                            context.InfoStaff.Where(s => s.StaffType == "installstaff").AsEnumerable()
                            .Select(d => new SelectListItem
                            {
                                Text = d.StaffName,
                                Value = d.StaffId,
                                Selected = false
                            }).ToList();
                    }
                }
                else
                {
                    List<SelectListItem> items = new List<SelectListItem>();
                    items.Add(new SelectListItem());

                    //车辆类型
                    ViewBag.VehicleType = new SelectList(items);

                    //终端类型(默认选中部标协议）
                    ViewBag.GpsType = new SelectList(items);

                    //终端版本号
                    ViewBag.GpsVersion = new SelectList(items);

                    //行驶记录仪版本号
                    ViewBag.TerminalVersion = new SelectList(items);

                    //车辆品牌
                    ViewBag.VehicleBrand = new SelectList(items);

                    //车辆颜色
                    ViewBag.VehicleColor = new SelectList(items);

                    //安装人员
                    ViewBag.InstallStaffId = new SelectList(items);
                }

                return View(vehicleToUpdate);

            }
            catch (System.Exception ex)
            {
                ViewBag.Message = "修改失败," + ex.Message;

                //车辆类型
                ViewBag.VehicleType =
                    context.Dictionary_Detail.Where(d => d.TypeID == "zd001").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicName,
                    }).ToList();

                //终端类型(默认选中部标协议）
                ViewBag.GpsType =
                    context.Dictionary_Detail.Where(d => d.TypeID == "gpstype").OrderBy(d => d.DicValue).AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicValue,
                        Selected = d.DicID == "bbxy"
                    }).ToList();

                //终端版本号
                ViewBag.GpsVersion =
                    context.Dictionary_Detail.Where(d => d.TypeID == "gpsversion" && d.Memo == "bbxy").OrderBy(d => d.DicValue).AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicValue,
                        Selected = d.DicID == "bzbb"
                    }).ToList();

                //行驶记录仪版本号
                ViewBag.TerminalVersion =
                    context.Dictionary_Detail.Where(d => d.TypeID == "terminalversion").OrderByDescending(d => d.DicID).AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicValue,
                        Selected = d.DicID == "xsjly2012"
                    }).ToList();

                //车辆品牌
                ViewBag.VehicleBrand =
                    context.Dictionary_Detail.Where(d => d.TypeID == "zd003").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicName,
                        Selected = false
                    }).ToList();

                //车辆颜色
                ViewBag.VehicleColor =
                    context.Dictionary_Detail.Where(d => d.TypeID == "zd006").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicName,
                        Selected = false
                    }).ToList();

                //安装人员
                ViewBag.InstallStaffId =
                    context.InfoStaff.Where(s => s.StaffType == "installstaff").AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.StaffName,
                        Value = d.StaffId,
                        Selected = false
                    }).ToList();

                return View(new InfoVehicle());
            }
        }

        public ActionResult GetGpsVersion(string parameters)
        {
            try
            {
                List<SelectListItem> list = context.Dictionary_Detail.Where(d => d.TypeID == "gpsversion" && d.Memo == parameters).OrderBy(d => d.DicValue).AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicValue
                    }).ToList();
                return Json(new { success = "true", message = CommonFunctions.ListToJsonStr(list) });                
            }
            catch (System.Exception ex)
            {
                return Json(new { success = "false", message = ex.Message });                            	
            }
            
        }

        public ActionResult GetTerminalVersion(string parameters)
        {
            try
            {
                List<SelectListItem> list = context.Dictionary_Detail.Where(d => d.TypeID == "terminalversion" && d.Memo == parameters).OrderByDescending(d => d.DicID).AsEnumerable()
                    .Select(d => new SelectListItem
                    {
                        Text = d.DicName,
                        Value = d.DicValue
                    }).ToList();
                return Json(new { success = "true", message = CommonFunctions.ListToJsonStr(list) });                
            }
            catch (System.Exception ex)
            {
                return Json(new { success = "false", message = ex.Message });                            	            	
            }
        }

        [MenuAuthorized("126")]
        public ActionResult OilBoxManage(string id)
        {
            ViewBag.VehicleNum = id;
            InfoOilBox oilbox = context.InfoOilBox.SingleOrDefault(o => o.vehicleNum == id);
            if (oilbox == null)
            {
                oilbox = new InfoOilBox();
            }
            return View(oilbox);
        }

        [HttpPost]
        [MenuAuthorized("126")]
        public ActionResult OilBoxManage(FormCollection form)
        {
            InfoOilBox box = context.InfoOilBox.SingleOrDefault(o => o.vehicleNum == form["vehicleNum"]);
            try
            {
                //更新车辆表中的数据
                InfoVehicle v = context.InfoVehicle.Single(o => o.Vehiclenum == form["vehicleNum"]);
                v.OilBoxVolumn = 0.0;
                v.IsOilBoxInited = true;
                if (!string.IsNullOrEmpty(form["oilCapacity"]))
                {
                    v.OilBoxVolumn = Convert.ToDouble(form["oilCapacity"]);
                }
                InfoOilBox b = box;
                if (box == null)
                {
                    box = new InfoOilBox();
                }
                else
                {
                    box.oilLeverType = "";
                    box.oilCapacity = null;
                    box.oilHeight = null;
                    box.oilLength = null;
                    box.oilWidth = null;
                    box.sampleData = "";
                    box.userId = "";
                    box.opeTime = "";
                }
                UpdateModel(box, form.ToValueProvider());
                //去掉结尾的分号
                if (!string.IsNullOrEmpty(box.sampleData) && box.sampleData.EndsWith(";"))
                {
                    box.sampleData = box.sampleData.Substring(0, box.sampleData.Length - 1);
                }
                box.opeTime = DateTime.Now.ToString();
                box.userId = CommonFunctions.GetLoginUser().UserId;
                if (b == null)
                {
                    context.InfoOilBox.InsertOnSubmit(box);
                }
                context.SubmitChanges();
                ViewBag.Message = "操作成功";
            }
            catch
            {
                ViewBag.Message = "操作失败";
            }
            return View(box);
        }

        public ActionResult ExportData()
        {
            if (Session["vehiclelist"] != null)
            {
                List<InfoVehicle> vehicles = Session["vehiclelist"] as List<InfoVehicle>;

                //-------------------------------表头读取开始------------------------------------------------
                StringBuilder sb = new StringBuilder();
                sb.Append("<table border='1' cellspacing='0' cellpadding='0'>");
                sb.Append("<tr><th>车辆内部编号</th><th>车牌号</th><th>车辆类别</th><th>信息（SIM）卡号</th><th>车辆车架号</th><th>发动机号</th><th>终端类型</th><th>终端版本号</th><th>车辆状态</th><th>安装日期</th><th>所属单位</th><th>油箱已初始化</th><th>备注</th></tr>");

                try
                {
                    foreach (InfoVehicle item in vehicles)
                    {
                        string name1, name2;
                        CommonDictionary.GpsTypeDic.TryGetValue(item.GPSType.ToString(), out name1);
                        item.GPSTypeName = name1;
                        CommonDictionary.GpsVersionDic.TryGetValue(item.GPSType.ToString() + item.GPSVersion.ToString(), out name2);
                        item.GPSVersionName = name2;
                        sb.Append("<tr>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.FInnerId + "</td>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.VehicleId + "</td>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.VehicleType + "</td>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.SIM + "</td>"); 
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.VIN + "</td>"); 
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.EngineId + "</td>"); 
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.GPSTypeName + "</td>"); 
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.GPSVersionName + "</td>"); 
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.VehiclecurState + "</td>"); 
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.InstallDate + "</td>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.InfoUnit.UNITNAME+ "</td>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + (item.IsOilBoxInited?"是":"否") + "</td>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.FMemo+"</td>");
                        sb.Append("</tr>");
                    }
                    sb.Append("</table>");
                    //------------------------------------------end----------------------------------------------------------------------------------
                    byte[] b = Encoding.GetEncoding("GB2312").GetBytes((sb.ToString()));
                    return File(b, @"application/ms-excel", Server.UrlPathEncode("车辆报表" + ".xls"));//输出档案给Client端
                }
                catch
                {
                    ViewBag.Message = "导出出错";
                    return View("ActionResult");
                }
            }
            else
            {
                ViewBag.Message = "数据已过期，请重新查询";
                return View("ActionResult");
            }
        }

        private void updateGpsType(InfoVehicle vehicle)
        {
            UpdateGpsType model = new UpdateGpsType();
            model.cmd = "UPDATETERMTYPE_TYPE";
            model.simId = vehicle.SIM;
            model.plate = vehicle.VehicleId;
            model.termId = vehicle.TerminalId;
            List<AttachType> attach = new List<AttachType>();
            if (vehicle.TerminalVersion != null)
            {
                string version = "0";
                if (vehicle.TerminalVersion == 0)
                {
                    version = "GBT19056_03_VERSION";
                }
                else if (vehicle.TerminalVersion == 1)
                {
                    version = "GBT19056_12_VERSION";
                }
                attach.Add(new AttachType() { type = "RECORDERDEV_TYPE", version = version });
            }
            if (vehicle.IsOffBump)
            {
                attach.Add(new AttachType() { type = "OILDEV_TYPE" });
            }
            model.attachType = attach;

            string gpsType = "0";
            string gpsVersion = "0";
            switch (vehicle.GPSType)
            {
                case 1:
                    gpsType = "HQ_PROTOCOL_TYPE";
                    break;
                case 2:
                    gpsType = "BB_PROTOCOL_TYPE";
                    switch (vehicle.GPSVersion)
                    {
                        case 0:
                            gpsVersion = "BB_PROTOCOL_VERSION";
                            break;
                        case 1:
                            gpsVersion = "ST_PROTOCOL_VERSION";
                            break;
                        case 2:
                            gpsVersion = "BSJ_PROTOCOL_VERSION";
                            break;
                        case 3:
                            gpsVersion = "BD_PROTOCOL_VERSION";
                            break;
                        case 4:
                            gpsVersion = "BSJBD_PROTOCOL_VERSION";
                            break;
                    }
                    break;
                case 3:
                    gpsType = "GL_PROTOCOL_TYPE";
                    switch (vehicle.GPSVersion)
                    {
                        case 0:
                            gpsVersion = "GLPRO_VERSION_100";
                            break;
                        case 1:
                            gpsVersion = "GLPRO_VERSION_200";
                            break;
                        case 2:
                            gpsVersion = "GLPRO_VERSION_320";
                            break;
                        case 3:
                            gpsVersion = "GLPRO_VERSION_505";
                            break;
                    }
                    break;
                case 4:
                    gpsType = "CX_PROTOCOL_TYPE";
                    switch(vehicle.GPSVersion)
                    {
                        case 0:
                            gpsVersion = "CONCOX_VERSION_181";
                            break;
                        case 1:
                            gpsVersion = "CONCOX_VERSION_185";
                            break;
                    }
                    break;
                case 5:
                    break;
            }

            model.type = gpsType;
            model.version = gpsVersion;
                    
            RealTimeSend.gpsAppNotify(vehicle.SIM,CommonFunctions.ObjectToJsonStr(model));
        }
    }
}
